package com.example.task1.ui.AllService.library;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.task1.R;
import com.example.task1.application.MyApplication;
import com.example.task1.base.BaseActivity;
import com.example.task1.bean.LibraryBean;
import com.example.task1.http.Api;
import com.example.task1.util.ApiResp;
import com.example.task1.util.CallBack;

import retrofit2.Call;

public class LibraryActivity extends BaseActivity {

    private RecyclerView rvList;
    private LibraryAdapter libraryAdapter;
    private LinearLayoutManager linearLayoutManager;
    private int pageNum = 1;
    private boolean isTrue = true;

    private void loadCommentList() {
        rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                if (libraryAdapter.getItemCount() - 1 == linearLayoutManager.findLastVisibleItemPosition() && isTrue) {
                    isTrue = false;
                    initData();
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_library);
        initView();
        initData();
        setAdapter();
        loadCommentList();
    }

    private void setAdapter() {
        libraryAdapter = new LibraryAdapter(this);
        linearLayoutManager = new LinearLayoutManager(this);
        rvList.setAdapter(libraryAdapter);
        rvList.setLayoutManager(linearLayoutManager);
    }

    private void initData() {
        Call<ApiResp> call = Api.api().get(MyApplication.TOKEN, "/prod-api/api/digital-library/library/list?pageNum=" + pageNum + "&pageSize=10");
        Api.send(call, LibraryBean.class, new CallBack<LibraryBean>() {
            @Override
            public void success(LibraryBean data) {
                if (libraryAdapter.getData().size() < data.getTotal()) {
                    isTrue = true;
                    libraryAdapter.setData(data.getRows());
                    pageNum++;
                } else {
                    MyApplication.show("没有更多数据了");
                }
            }

            @Override
            public void error(String msg) {

            }
        });
    }

    @Override
    public String getMyTitle() {
        return "数字图书馆";
    }

    private void initView() {
        rvList = findViewById(R.id.rv_list);
    }
}